package com.sendmail;

import org.apache.log4j.Logger;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

/**
 * 发送普通邮件，
 * 接受普通邮件 发送带有附件的邮件，
 * 接收带有附件的邮件 发送html形式的邮件，
 * 接受html形式的邮件 发送带有图片的邮件等做了一个总结。
 */
public class Sendemail {
	private static final Logger logger = Logger.getLogger(Sendemail.class);
	public static void main(String[] args){
		Sendemail sendmail = new Sendemail(
				"smtp.sina.com",//host
				"",//port
				"malili_test@sina.com",//发件服务器邮箱地址
				"maliliTest",//密码
				"head",//其他参数
				"headvalue",//其他参数
				"lilima@Ctrip.com",//收件人
				"",//抄送人
				"malili_test@sina.com",//发件人
				"测试标题",//标题
				"测试内容",//内容
				""//其他参数，可填写可不填
		);
		try{
			sendmail.send();
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}

	// 邮箱服务器
	private String host = "";
	//端口号
	private String port = "";

	// 这个是你的邮箱用户名
	private String username = "";

	// 你的邮箱密码
	private String password = "";

	private String mail_head_name = "";

	private String mail_head_value = "";

	private String mail_to = "";

	private String mail_cc = "";

	private String mail_from = "";

	private String mail_subject = "";

	private String mail_body = "";

	private String personalName = "";

	private String filename = "";
	
	private String httpAddress="";
	
	private Vector<String> file = new Vector<String>(); // 用于保存发送附件的文件名的集合

	public Sendemail(){
	}

	public Sendemail(String host, String port, String username, String password,
					 String mail_head_name, String mail_head_value, String mail_to,
					 String mail_cc, String mail_from, String mail_subject,
					 String mail_body, String personalName){
		this.host = host;
		this.port = port;
		this.username = username;
		this.password = password;
		this.mail_head_name = mail_head_name;
		this.mail_head_value = mail_head_value;
		this.mail_subject = mail_subject;
		this.mail_body = mail_body;
		this.mail_from = mail_from;
		this.mail_to = mail_to;
		this.mail_cc = mail_cc;
	}

	/**
	 * 该方法用于收集附件名
	 */
	public void addAttachfile(String fname){
		file.addElement(fname);
	}

	/**
	 * 此段代码用来发送普通电子邮件
	 */
	public boolean send() throws Exception{
		boolean b = true;
		try {
			Properties props = new Properties(); // 获取系统环境
			
			Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.port", port);
			Session session = Session.getDefaultInstance(props, auth);
			// 设置session,和邮件服务器进行通讯。
			MimeMessage message = new MimeMessage(session);
			BodyPart bp = new MimeBodyPart();

			message.setSubject(mail_subject); // 设置邮件主题

			Multipart mp = new MimeMultipart();

			MimeBodyPart mbp = new MimeBodyPart();

			if (!file.isEmpty()){// 有附件
				Enumeration<String> efile = file.elements();
				while (efile.hasMoreElements())
				{
					mbp = new MimeBodyPart();
					filename = efile.nextElement().toString(); // 选择出每一个附件名
					// System.out.println("filename---"+filename);
					FileDataSource fds = new FileDataSource(filename); // 得到数据源
					mbp.setDataHandler(new DataHandler(fds)); // 得到附件本身并至入BodyPart
					// mbp.setFileName(fds.getName()); //得到文件名同样至入BodyPart
					mbp
							.setFileName(MimeUtility.encodeText(filename
									.substring(filename.lastIndexOf("\\") + 1,
											filename.length())));
					mp.addBodyPart(mbp);
				}
				file.removeAllElements();
			}
			// 发送带HTML格式邮件
			bp.setContent(
					"<meta http-equiv=Content-Type content=text/html; charset=utf-8>"
							+ mail_body, "text/html;charset=UTF-8");
			mp.addBodyPart(bp);
			message.setContent(mp); // Multipart加入到信件
			// 设置邮件标题
			message.setSentDate(new Date()); // 设置邮件发送日期
			Address address = new InternetAddress(mail_from, personalName);
			message.setFrom(address); // 设置邮件发送者的地址
			// 每次发送都加上XXXX的邮箱地址
			Address toAddress = null;
			if (mail_to != null && !"".equals(mail_to)){
				String[] mail_to_item_i = mail_to.split(",");
				for (String mail_to_i : mail_to_item_i){
					String[] mail_to_item_j = mail_to_i.split(";");
					for (String mail_to_j : mail_to_item_j){
						toAddress = new InternetAddress(mail_to_j); // 设置邮件接收方的地址
						message.addRecipient(Message.RecipientType.TO,
								toAddress);
					}
				}
			}
			if (mail_cc != null && !"".equals(mail_cc)){
				String[] mail_cc_item_i = mail_cc.split(",");
				for (String mail_cc_i : mail_cc_item_i){
					String[] mail_cc_item_j = mail_cc_i.split(";");
					for (String mail_cc_j : mail_cc_item_j){
						Address ccAddrss = new InternetAddress(mail_cc_j);// 设置邮件抄送接接收方的地址
						message
								.addRecipient(Message.RecipientType.CC,
										ccAddrss);
					}
				}
			}
			if (mail_to != null && !"".equals(mail_to)){
				Transport.send(message); // 发送邮件
				System.out.println("send ok!");
				b = true;
			}
		} catch (Exception ex){
			ex.printStackTrace();
			b = false;
			throw ex;
		}
		return b;
	}

	/**
	 * 用来进行服务器对用户的认证
	 */
	public class Email_Autherticator extends Authenticator{
		public Email_Autherticator(){
			super();
		}

		public Email_Autherticator(String user, String pwd){
			super();
			username = user;
			password = pwd;
		}
 
		@Override
		public PasswordAuthentication getPasswordAuthentication(){
			return new PasswordAuthentication(username, password);
		}
	}

	public String getHost(){
		return host;
	}

	public void setHost(String host){
		this.host = host;
	}

	public String getUsername(){
		return username;
	}

	public void setUsername(String username){
		this.username = username;
	}

	public String getPassword(){
		return password;
	}

	public void setPassword(String password){
		this.password = password;
	}

	public String getMail_head_name(){
		return mail_head_name;
	}

	public void setMail_head_name(String mail_head_name){
		this.mail_head_name = mail_head_name;
	}

	public String getMail_head_value(){
		return mail_head_value;
	}

	public void setMail_head_value(String mail_head_value){
		this.mail_head_value = mail_head_value;
	}

	public String getMail_to(){
		return mail_to;
	}

	public void setMail_to(String mail_to){
		this.mail_to = mail_to;
	}

	public String getMail_from(){
		return mail_from;
	}

	public void setMail_from(String mail_from){
		this.mail_from = mail_from;
	}

	public String getMail_subject(){
		return mail_subject;
	}

	public void setMail_subject(String mail_subject){
		this.mail_subject = mail_subject;
	}

	public String getMail_body(){
		return mail_body;
	}

	public void setMail_body(String mail_body){
		this.mail_body = mail_body;
	}

	public String getPersonalName(){
		return personalName;
	}

	public void setPersonalName(String personalName){
		this.personalName = personalName;
	}

	public String getMail_cc(){
		return mail_cc;
	}

	public void setMail_cc(String mail_cc){
		this.mail_cc = mail_cc;
	}

	public String getHttpAddress() {
		return httpAddress;
	}

	public void setHttpAddress(String httpAddress) {
		this.httpAddress = httpAddress;
	}

	public static void sendMail(String content){

		String title = "网络爬虫网站采集异常";
		Sendemail sendmail = new Sendemail(
			"smtp@163.com",//host
			"25",//port
			"username@163.com",//发件服务器邮箱地址
			"userpass",//密码
			"head",//其他参数
			"headvalue",//其他参数
			"lilima@Ctrip.com",//收件人
			"",//抄送人
			"username@163.com",//发件人
			title,//标题
			content,//内容
			""//其他参数，可填写可不填
		);
		try{
			sendmail.send();
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}
}
